package com.app.mingluxing.location;


import android.app.Dialog;
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.app.mingluxing.R;
import com.app.mingluxing.base.BaseActivity;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.LogUtil;
import com.app.mingluxing.widget.MySeekBar;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.DotOptions;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;

/**
 * 添加安全区域
 *
 * @author fc
 */
public class AddSafeAreaActivity extends BaseActivity {

    private TextView tv_title;
    //    private ImageButton iv_back;
//    private String currentWatchId;
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MySeekBar mSeekBar;
    protected boolean isTouchSeeked = false;
    private SeekBar.OnSeekBarChangeListener mSeekBarListener;
    private Button btn;
    boolean isFirstLoc = true;// 是否首次定位
    //    private String userId;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LatLng mLatLng = null;
//    private LatLng ll = null;
//    private EditText et_name;
    /**
     * 安全区域的半径
     */
    protected int mRadius;
    //    protected String mSafeAreaName;
    private Dialog addSafeAreaDialog;
    // private LatLng fromScreenLocation;
    // private Point screenCenter;
//    private RingView mRingView;
    private String id;
    //    private float metersToEquatorPixels;// 将米转化成地图上的px值
    private ImageView iv_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.add_safe_area);
//        mApplication.addActivity(this);
        id = getIntent().getStringExtra("id");
        //进出动画效果
        overridePendingTransition(R.anim.translate_in, R.anim.translate_out);
//		mBaiduMap.setMyLocationEnabled(true);
        // 加载控件
        initView();

//        initValue();

        setListener();

    }

//    /**
//     * 初始化变量
//     */
//    private void initValue() {
////        mSeekBar.setProgress(mRadius);
//        mRadius = 100;
//        createPoint(mBaiduMap.getMapStatus().target, mRadius);
//
//    }

    private void setListener() {
//        iv_back.setOnClickListener(this);
        btn.setOnClickListener(this);

        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {

            @Override
            public void onMapLoaded() {
                LogUtil.e("tag", "onMapLoaded 地图加载完成 ");
//                // 地图加载完成
//                changRadiu();
//                // 获得当前点在地图上的的经纬度
//                mLatLng = mBaiduMap.getProjection().fromScreenLocation(
//                        new Point(CommonUtils.getScreenSize(getApplication())[0] / 2,
//                                CommonUtils.getScreenSize(getApplication())[1] / 2));

                mLatLng= new LatLng(mApplication.myLatitude, mApplication.myLongitude);
//                mLatLng= mBaiduMap.getMapStatus().target;

//                initValue();
                mRadius = 100;
                createPoint(mLatLng, mRadius);

            }
        });
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {

            @Override
            public void onMapStatusChangeStart(MapStatus arg0) {

                LogUtil.e("TAG", "onMapStatusChangeStart");
//                mBaiduMap.clear();
//                createPoint(arg0.target, mRadius);
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus arg0) {
                // test();

                // createPoint(fromScreenLocation, mRadius);

//                 mRingView.changeRadiu(radius);
//                LogUtil.e("TAG", "onMapStatusChangeFinish:");


            }

            @Override
            public void onMapStatusChange(MapStatus arg0) {
                LogUtil.e("TAG", "onMapStatusChange");
//                changRadiu();
                createPoint(arg0.target, mRadius);

            }

        });

        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {

            @Override
            public boolean onMapPoiClick(MapPoi arg0) {
                return false;
            }

            @Override
            public void onMapClick(LatLng arg0) {
                // 将marker所在的经纬度的信息转化成屏幕上的坐标
                // Point p = mBaiduMap.getProjection().toScreenLocation(arg0);
                // Log.e("AddSafeAreaActivity", "--!" + p.x + " , " + p.y);
                // mLatLng = arg0;
                // createPoint(arg0, 1000);
            }
        });

        /**
         * 进度拖动条监听器
         */
        mSeekBarListener = new SeekBar.OnSeekBarChangeListener() {
            // 通知进度已经被修改
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
//                Log.e("aaa", "onProgressChanged");
                if (isTouchSeeked) {
                    mRadius = progress * 10 + 100;
                    mSeekBar.showSeekDialog(progress * 10 + 100 + "m");// 动态展示当前进度

                    LogUtil.e("tag", "区域的半径==" + mRadius);

                    LatLng target = mBaiduMap.getMapStatus().target;

                    createPoint(target, mRadius);
//                    createPoint(mLatLng, mRadius);
//                    changRadiu();

                } else {
                    mSeekBar.hideSeekDialog();
                }
            }

            // 通知用户已经开始一个触摸拖动手势
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // showControlView(3600000);
//                Log.e("aaa", "onStartTrackingTouch");
                isTouchSeeked = true;

            }

            // 通知用户触摸手势已经结束
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
//                Log.e("aaa", "onStopTrackingTouch");
                // Message msg = Message.obtain();
                // msg.what = PROGRESS_SEEKTO;
                // msg.arg1 = seekBar.getProgress();
                // mHandler.removeMessages(PROGRESS_SEEKTO);
                // mHandler.sendMessageAtTime(msg, 1000);// 1秒之后开始发送更新进度的消息
                isTouchSeeked = false;
                mSeekBar.hideSeekDialog();
                // showControlView(sDefaultTimeout);
            }
        };
        mSeekBar.setOnSeekBarChangeListener(mSeekBarListener);
    }

//    public static int meterToPixels(MapView map, int scale) {
//
//        // 得到当前中心位置对象
//        GeoPoint geoPoint = map.getMapCenter();
//        // 得到当前中心位置纬度
//        double latitude = geoPoint.getLatitudeE6() / 1E6;
//        // 得到象素数，比如当前比例尺是1/10000，比如scale=10000，对应在该纬度应在地图中绘多少象素
//        // 参考http://rainbow702.iteye.com/blog/1124244
//        return (int) (map.getProjection().metersToEquatorPixels(scale) / (Math
//                .cos(Math.toRadians(latitude))));
//
//    }


    private void initView() {

        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.add_safe_area));
        iv_back = (ImageView) findViewById(R.id.iv_back);

        iv_back.setOnClickListener(this);

        mSeekBar = (MySeekBar) findViewById(R.id.seek_progress);
        mSeekBar.setMax(90);// 最大值90 因为有个默认的100
//        mSeekBar.setMax(100);// 最大值
        // 圆形控件
//        mRingView = (RingView) findViewById(R.id.ringView);
        // start = (TextView) findViewById(R.id.start);
        // end = (TextView) findViewById(R.id.end);
        btn = (Button) findViewById(R.id.btn);

        // 地图初始化
        // 获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();

        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(16.0f);
        mBaiduMap.setMapStatus(msu);

        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(getApplicationContext());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(100000);
//        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式
//        option.setIsNeedAddress(true);
        mLocClient.setLocOption(option);
        mLocClient.start();

    }

//    /**
//     * 改变半径
//     */
//    private void changRadiu() {
////        LogUtil.e("tag", " === 改变半径 ==== :" + mRadius);
//        // px
//        metersToEquatorPixels = mBaiduMap.getProjection().metersToEquatorPixels(mRadius);
//        mRingView.changeRadiu(metersToEquatorPixels);
//    }

    /**
     * 创建覆盖物
     */
    private void createPoint(LatLng latlng, int radius) {

//        LogUtil.e("tag", " createPoint radius:" + radius);

        mBaiduMap.clear();

        // 添加圆
        mLatLng = latlng;
        if (mLatLng == null) {
            // 默认点
            mLatLng = new LatLng(39.86923, 116.397428);
        }
        OverlayOptions ooCircle = new CircleOptions().fillColor(0x4d35a9e2)
                .center(mLatLng).stroke(new Stroke(5, 0x8035a9e2))
                .radius(radius);

        mBaiduMap.addOverlay(ooCircle);

        // 添加点
        // LatLng llDot = new LatLng(39.90923, 116.447428);
        OverlayOptions ooDot = new DotOptions().center(mLatLng).radius(6)
                .color(0xff35a9e2);
        mBaiduMap.addOverlay(ooDot);

        // 定位到该点
        // MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(mLatLng);
        // mBaiduMap.setMapStatus(u);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mLocClient != null)
            // 退出时销毁定位
            mLocClient.stop();

        if (mBaiduMap != null)
            // 关闭定位图层
            mBaiduMap.setMyLocationEnabled(false);

        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
        }

        mApplication.cancelPendingRequests(getClass().getName());

    }

    @Override
    public void onResume() {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();

    }

    /**
     * 创建围栏
     */
    private void createSafeArea(String id, String lat, String lng) {

        JSONObject j = new JSONObject();
        j.put("id", id);
        j.put("radius", mRadius + "");
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("lat", lat);
        j.put("lon", lng);
        j.put("areaName", et_area_name.getText().toString().trim());

        HttpUtil.setPostRequest("创建中..", this, Constant.WEB_ROOT + Constant.ADDAREA,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(et_area_name.getWindowToken(), 0);

                            if (addSafeAreaDialog != null && addSafeAreaDialog.isShowing()) {
                                addSafeAreaDialog.dismiss();
                            }

                            org.json.JSONObject j = new org.json.JSONObject(str);
                            if (Constant.STATUS_SUCCESS == j.getInt("code"))
                                showToast("添加成功");
                            else
                                showToast(Constant.showErrorMsg(j.getInt("code"), AddSafeAreaActivity.this));


                        } catch (Exception e) {
                            e.printStackTrace();
//                            showToast("创建失败");
                        }

                    }
                }, null);
    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {
            case R.id.iv_back://返回

                finish();
                break;

            case R.id.btn://添加安全围栏

                addSafeArea();

                break;

            case R.id.tv_create://创建安全围栏

                if (CommonUtils.isNull(et_area_name.getText().toString().trim())) {
                    showToast("请输入安全区域名称");
                    return;
                }

                getData();
                break;

            case R.id.tv_cancle://取消

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et_area_name.getWindowToken(), 0);

                if (addSafeAreaDialog != null && addSafeAreaDialog.isShowing()) {
                    addSafeAreaDialog.dismiss();
                }
                break;
            default:
                break;
        }
    }

    /**
     * //     * 添加安全围栏
     */
    private EditText et_area_name;

    private void addSafeArea() {

        addSafeAreaDialog = new Dialog(this, R.style.no_title);

        addSafeAreaDialog.setCancelable(false);
        addSafeAreaDialog.setCanceledOnTouchOutside(false);
        addSafeAreaDialog.show();

        addSafeAreaDialog.setContentView(R.layout.dialog_add_safe_area);

        et_area_name = (EditText) addSafeAreaDialog.findViewById(R.id.et_area_name);
        TextView tv_create = (TextView) addSafeAreaDialog.findViewById(R.id.tv_create);
        TextView tv_cancle = (TextView) addSafeAreaDialog.findViewById(R.id.tv_cancle);

        et_area_name.post(new Runnable() {

            @Override
            public void run() {
                InputMethodManager im = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                im.showSoftInput(et_area_name, 0);
            }
        });

        tv_create.setOnClickListener(this);
        tv_cancle.setOnClickListener(this);

    }

    private void getData() {

        if (mLatLng == null) {
//            LogUtil.e("AddSafeAreaActivity", "mLatLng==null");
            return;
        }
        double lat = mLatLng.latitude;
        double lng = mLatLng.longitude;
        if (!CommonUtils.isNull(id) && !CommonUtils.isNull(lat + "") && !CommonUtils.isNull(lng + "")) {
            createSafeArea(id, lat + "", lng + "");
        }
//        else {
//            showToast("参数为空");
//        }

    }

    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);

            if (isFirstLoc) {
                isFirstLoc = false;
                mLatLng = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(mLatLng);
                mBaiduMap.animateMapStatus(u);
            } else {
                mLatLng = mBaiduMap.getProjection().fromScreenLocation(new Point(CommonUtils.getScreenSize(getApplication())[0] / 2,
                        CommonUtils.getScreenSize(getApplication())[1] / 2));
            }

        }



        public void onReceivePoi(BDLocation poiLocation) {


//            int i = CommonUtils.getScreenSize(getApplication())[0];
//            int j = CommonUtils.getScreenSize(getApplication())[1];
        }
    }





    @Override
    public void finish() {
        super.finish();
        //进出动画效果
        overridePendingTransition(R.anim.translate_in, R.anim.translate_out);
    }
}



